package org.example.service.impl;

import org.example.domain.Comment;
import org.example.mapper.PostMapper;
import org.springframework.transaction.PlatformTransactionManager;
import org.example.domain.Post;
import org.example.repository.PostRepository;
import org.example.repository.CommentRepository;
import org.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashSet;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;

    /***
     * 获取所有帖子
     * @param userId 用户ID，用于检查点赞状态
     * @return
     */
    @Override
    public List<Post> getAllPosts(String userId) {
        // 使用按创建时间倒序的查询方法
        List<Post> posts = postRepository.findAllByOrderByCreateTimeDesc();
        
        // 处理每个帖子的评论和点赞信息
        for (Post post : posts) {
            // 初始化 likedBy 集合
            if (post.getLikedBy() == null) {
                post.setLikedBy(new ArrayList<>());
            }
            
            // 设置点赞数
            post.setLikes(post.getLikedBy().size());
            
            // 获取帖子的父级评论
            List<Comment> parentComments = commentRepository.findByPostIdAndParentIdIsNull(post.getId());
            
            // 设置每个评论的回复数
            for (Comment comment : parentComments) {
                long replyCount = commentRepository.countByParentId(comment.getId());
                comment.setReplyCount((int) replyCount);
                comment.setHasLowerComment(replyCount > 0);
            }
            
            // 设置帖子的评论
            post.setComments(parentComments);
            
            // 设置总评论数（包括回复）
            long totalComments = parentComments.size() + 
                parentComments.stream()
                    .mapToLong(comment -> commentRepository.countByParentId(comment.getId()))
                    .sum();
            post.setCommentCount((int) totalComments);
            
            // 7. 处理点赞状态
            if (userId != null && !userId.isEmpty()) {
                boolean hasLiked = post.getLikedBy().contains(userId);
                if (hasLiked && !post.getLikedBy().contains(userId)) {
                    post.getLikedBy().add(userId);
                }
            }
        }
        
        return posts;
    }

    /**
     * 创建新帖子
     * @param post
     * @return
     */
    @Override
    public Post createPost(Post post) {
        // 定义事务属性
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        // 开启事务
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            //绑定文件表
            postMapper.bindfile(post.getId(), post.getFileIds());
            //根据文件id获取所有
            List<String> urls=postMapper.getUrlByFileIds(post.getFileIds());
            // 设置初始值
            post.setId(java.util.UUID.randomUUID().toString());
            post.setCreateTime(new Date());
            post.setUpdateTime(new Date());
            post.setLikes(0);
            post.setUrls(urls);
            post.setLikedBy(new ArrayList<>()); // 初始化点赞用户列表

            // 保存到数据库
            Post save = postRepository.save(post);
            transactionManager.commit(status);
            return save;
        } catch (Exception e) {
            // 回滚事务
            transactionManager.rollback(status);
            throw e;
        }
    }

    /**
     * 添加评论
     * @param postId
     * @param comment
     * @return
     */
    @Override
    public Post addComment(String postId, Comment comment) {
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new RuntimeException("帖子不存在"));
        
        comment.setId(java.util.UUID.randomUUID().toString());
        comment.setCreateTime(new Date());
        
        if (post.getComments() == null) {
            post.setComments(new ArrayList<>());
        }
        post.getComments().add(comment);
        post.setUpdateTime(new Date());
        
        return postRepository.save(post);
    }

    /***
     * 获取一个帖子的总评论数
     * @param postId
     * @return
     */
    @Override
    public int getTotalCountByPostId(String postId) {
        return commentRepository.countByPostId(postId);
    }

    /**
     * 点赞
     * @param postId
     * @param userId
     * @return
     */
    @Override
    public Post likePost(String postId, String userId) {
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new RuntimeException("帖子不存在"));
        
        // 检查用户是否已点赞
        if (post.getLikedBy() != null && post.getLikedBy().contains(userId)) {
            throw new RuntimeException("用户已点赞");
        }
        
        // 初始化likedBy列表（如果为null）
        if (post.getLikedBy() == null) {
            post.setLikedBy(new ArrayList<>());
        }
        
        // 增加点赞数并记录用户
        post.setLikes(post.getLikes() + 1);
        post.getLikedBy().add(userId);
        post.setUpdateTime(new Date());
        
        return postRepository.save(post);
    }
}
